o0package com.atguigu.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * Date:2020/9/18
 * Author:ybc
 * Description:
 */
public class UpServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);

        try {
            //解析当前浏览器到服务器的请求，获取请求参数
            List<FileItem> fileItems = servletFileUpload.parseRequest(request);
            for (FileItem fileItem : fileItems) {
                //isFormField()判断当前浏览器提交的数据是否是一个普通的form数据（非文件）
                if(!fileItem.isFormField()){
                    //获取上传文件的表单元素的name属性值
                    String fieldName = fileItem.getFieldName();
                    //获取上传的文件名
                    String fileName = fileItem.getName();
                    //使用UUID替换当前上传文件的名字，避免文件的重名覆盖问题
                    String uuid = UUID.randomUUID().toString().replaceAll("-","");
                    String hzName = fileName.substring(fileName.lastIndexOf("."));
                    fileName = uuid + hzName;
                    //获取当前工程的编译路径，即out
                    String photoPath = request.getServletContext().getRealPath("photo");
                    //判断photoPath是否存在，若不存在则创建
                    File file = new File(photoPath);
                    if(!file.exists()){
                        file.mkdir();
                    }
                    String finalPath = photoPath + File.separator + fileName;
                    //文件上传
                    fileItem.write(new File(finalPath));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
